package org.microframework.cloud.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * IP限流解析器
 * 根据请求IP地址进行限流
 */
@Slf4j
@Component
public class IpKeyResolver implements KeyResolver {

    private static final String UNKNOWN = "unknown";

    @Override
    public Mono<String> resolve(ServerWebExchange exchange) {
        String ip = getIpAddress(exchange);
        log.debug("获取到客户端IP: {}", ip);
        return Mono.just(ip);
    }

    /**
     * 获取真实IP地址
     */
    private String getIpAddress(ServerWebExchange exchange) {
        String ip = Objects.requireNonNull(exchange.getRequest().getRemoteAddress()).getAddress().getHostAddress();
        
        // 获取X-Forwarded-For中的IP
        String xff = exchange.getRequest().getHeaders().getFirst("X-Forwarded-For");
        if (xff != null && !xff.isEmpty() && !UNKNOWN.equalsIgnoreCase(xff)) {
            // 多次反向代理后会有多个IP值，第一个为真实IP
            int index = xff.indexOf(",");
            if (index != -1) {
                return xff.substring(0, index);
            } else {
                return xff;
            }
        }
        
        // 获取X-Real-IP
        String xrip = exchange.getRequest().getHeaders().getFirst("X-Real-IP");
        if (xrip != null && !xrip.isEmpty() && !UNKNOWN.equalsIgnoreCase(xrip)) {
            return xrip;
        }
        
        return ip;
    }
} 